package com.greatwall.hip.cms.controller;

import com.greatwall.hip.cms.entity.User;
import com.greatwall.hip.cms.model.Result;
import com.greatwall.hip.cms.service.UserService;
import com.greatwall.hip.cms.shiro.JWTTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author TianLei
 * @version V1.0
 */
@RestController
@Api(tags = "登录模块", value = "用户登录")
public class LoginController {

    @Autowired
    private UserService userService;

    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody User loginUser){
        // 用户名密码校验
        User user = userService.queryByLoginName(loginUser.getLoginName());
        if (user == null){
            return Result.fail("无此用户");
        }
        if (!user.getPassword().equalsIgnoreCase(new Md5Hash(loginUser.getPassword()).toString())){
            return Result.fail("用户名或密码错误");
        }

        // 生成令牌
        String token = JWTTokenUtil.sign(loginUser.getLoginName(), loginUser.getPassword());

        return Result.success(token);
    }

}
